<script lang="ts" setup>
import { ref } from 'vue'
import { isEmpty } from '../../utils/common.ts'

const formRules = {
  user_id: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur',
    },
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur',
    },
  ],
}

const formModel = ref({
  user_id: '',
  username: '',
  role: '',
  authority: '',
})

const showDialog = ref(false)
const cancelDialog = () => {
  showDialog.value = false
  formModel.value = ''
}

const formRef = ref()
const emit = defineEmits(['success'])
const confirmDialog = async () => {
  await formRef.value.validate()
  formModel.value.id
    ? await artEditChannelService(formModel.value)
    : await artAddChannelService(formModel.value)
  ElMessage({
    type: 'success',
    message: formModel.value.id ? '编辑成功' : '添加成功',
  })
  showDialog.value = false
  formModel.value = ''
  emit('success')
}
const open = async (row) => {
  showDialog.value = true
  if (!isEmpty(row)) {
    formModel.value = { ...row }
    console.log(formModel.value)
  }
}

defineExpose({
  open,
})
</script>

<template>
  <el-dialog
    v-model="showDialog"
    :title="formModel.user_id ? '编辑分类' : '添加分类'"
    width="500"
    center
    @close="cancelDialog"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="formRules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="用户id" prop="user_id">
        <el-input
          v-model="formModel.user_id"
          :disabled="formModel.user_id !== ''"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formModel.username" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-input v-model="formModel.role" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="authority">
        <el-input v-model="formModel.authority" minlength="1" maxlength="15"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="confirmDialog"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
